#!/bin/bash

# ============================================
# 修复 Nginx 配置路径
# ============================================

echo "=== 检查当前情况 ==="

# 1. 获取当前实际路径
CURRENT_DIR=$(pwd)
echo "当前目录: $CURRENT_DIR"

# 2. 确认 dist 目录的实际路径
if [ -f "dist/index.html" ]; then
    DIST_PATH="$CURRENT_DIR/dist"
    echo "✓ 找到 dist 目录: $DIST_PATH"
else
    echo "✗ 当前目录没有 dist 目录"
    echo "请先 cd 到包含 dist 目录的位置"
    exit 1
fi

# 显示完整路径
FULL_DIST_PATH=$(readlink -f "$DIST_PATH")
echo "完整路径: $FULL_DIST_PATH"

# 3. 检查 Nginx 配置文件
NGINX_CONF="/etc/nginx/conf.d/frontend.conf"
echo ""
echo "=== 检查 Nginx 配置 ==="

if [ -f "$NGINX_CONF" ]; then
    echo "当前配置中的 root 路径:"
    grep "root" "$NGINX_CONF" | head -1
else
    echo "✗ 配置文件不存在: $NGINX_CONF"
    exit 1
fi

# 4. 更新配置文件
echo ""
echo "=== 更新配置 ==="
sudo sed -i "s|root.*;|root $FULL_DIST_PATH;|" "$NGINX_CONF"

echo "✓ 配置已更新"
echo "新的 root 路径:"
grep "root" "$NGINX_CONF" | head -1

# 5. 验证配置
echo ""
echo "=== 验证配置 ==="
if sudo nginx -t; then
    echo "✓ 配置测试通过"
else
    echo "✗ 配置测试失败"
    exit 1
fi

# 6. 重新加载
echo ""
echo "=== 重新加载 Nginx ==="
sudo systemctl reload nginx

# 7. 测试
echo ""
echo "=== 测试访问 ==="
sleep 1
curl -s http://localhost | head -20

echo ""
echo ""
echo "=== 如果仍然显示默认页面，可能需要检查 ==="
echo "1. 主配置文件是否包含 frontend.conf:"
echo "   grep -r 'include.*conf.d' /etc/nginx/"
echo ""
echo "2. 检查是否有其他 server 块干扰:"
echo "   sudo nginx -T | grep -A 5 'server_name'"

